import os
from flask import Blueprint, request, jsonify, current_app,send_from_directory, send_file,render_template
from utilsapp.mysql_con import db_pagelist, db_connect, db_delete, db_update,db_insert
from utilsapp.common import assign_value, parsing_data_id
from utilsapp import utils
import shutil


bluePrint = Blueprint('store', __name__)
tableName = 'store'

@bluePrint.route('/getlist', methods=["post"])
def table_list():
    script_dir = os.path.dirname(os.path.abspath(__name__))
    folder_path = script_dir + '/static/store/' + request.json['url']
    if not os.path.exists(folder_path):
        os.mkdir(folder_path)
    items_info = []
    for item_name in os.listdir(folder_path):
        item_path = os.path.join(folder_path, item_name)
        if os.path.isfile(item_path):
            item_info = {
            'name': item_name,
            'type': 'file',
            'size': os.path.getsize(item_path),
            'last_modified': os.path.getmtime(item_path),
            'file_type': os.path.splitext(item_name)[1]
            }
        elif os.path.isdir(item_path):
            item_info = {
            'name': item_name,
            'type': 'folder',
            'size': sum(os.path.getsize(os.path.join(root, file)) for root, _, files in os.walk(item_path) for file in files),
            'last_modified': os.path.getmtime(item_path)
            }
        items_info.append(item_info)
    return utils.ok(items_info)

@bluePrint.route('/download', methods=["post"])
def download():
    try:
        script_dir = os.path.dirname(os.path.abspath(__name__))
        folder_path = script_dir + '/static/store/' + request.json['url']
        return send_from_directory(folder_path, request.json['name'], as_attachment=True)
    except Exception as e:
        return jsonify({'code': -1, 'msg': '下载异常'}), 200
    
@bluePrint.route('/upload', methods=['POST'])
def upload():
    try:
        if 'file' not in request.files:
            return jsonify({'code': -1, 'msg': '空文件'}), 200
        file = request.files['file']
        if file.filename == '':
            return jsonify({'code': -1, 'msg': '空文件'}), 200
        script_dir = os.path.dirname(os.path.abspath(__name__))
        folder_path = script_dir + '/static/store/' + request.form['url']
        print(file.filename,folder_path)
        ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg','txt','zip','docx','doc','docx','xlsx','7z','mp3','mp4','html','jar','rar','ppt','sql','folder'}
        if ('.' in file.filename and file.filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS) == False:
            return jsonify({'code': -1, 'msg': '上传失败,非法文件类型'}), 200
        file.save(folder_path + '/' + file.filename)
        return jsonify({'code': 0, 'msg': '上传成功'}), 200
    except Exception as e:
        return jsonify({'code': -1, 'msg': '上传异常'}), 200
    
@bluePrint.route('/delete', methods=["post"])
def delete():
    script_dir = os.path.dirname(os.path.abspath(__name__))
    folder_path = script_dir + '/static/store/' + request.json['url'] + request.json['name']
    try:
        shutil.rmtree(folder_path) if request.json['type'] == 'folder' else os.remove(folder_path)
        return jsonify({'code': 0, 'msg': '删除成功'}), 200
    except OSError as e:

        return jsonify({'code': -1, 'msg': '删除失败'}), 200
        

@bluePrint.route('/add', methods=["post"])
def add():
    script_dir = os.path.dirname(os.path.abspath(__name__))
    folder_path = script_dir + '/static/store/' + request.json['url']
    new_folder_path = os.path.join(folder_path, request.json['name'])
    try:
        os.mkdir(new_folder_path)
        return jsonify({'code': 0, 'msg': '文件夹创建成功'}), 200
    except FileExistsError:
        return jsonify({'code': -1, 'msg': '同步文件夹已存在'}), 200
    except OSError as e:
        return jsonify({'code': -1, 'msg': '文件夹创建失败'}), 200